import { createRequestTypes } from '@UTILS/reduxHelper'
import { createReducer } from 'reduxsauce'
import { REHYDRATE } from 'redux-persist/es/constants'
import { CHANGE_MED_RECORD_STATUS, SET_MED_RECORD_FIELD } from '@ACTIONS/medRecord';

export const GET_MED_RECORD = createRequestTypes('GET_MED_RECORD')

const INITIAL_STATE = {
  loadingMedRecord: true,
  error: '',
  medRecordDetail: {},
}
const rehydrate = (state, { payload }) => {
  if (payload && payload.medRecord) {
    return { ...INITIAL_STATE, ...payload.medRecord }
  }
  return {
    ...state
  }
}

export default createReducer(INITIAL_STATE, {
  [REHYDRATE]: rehydrate,
  [GET_MED_RECORD.REQUEST]: state => ({
    ...state,
    loadingMedRecord: true,
    error: '',
    medRecordDetail: {}
  }),
  [GET_MED_RECORD.SUCCESS]: (state, { data }) => (
    {
      ...state,
      loadingMedRecord: false,
      error: '',
      medRecordDetail: data
    }
  ),
  [GET_MED_RECORD.FAILURE]: (state, { error }) => ({
    ...state,
    loadingMedRecord: false,
    error
  }),
  [CHANGE_MED_RECORD_STATUS.REQUEST]: (state, { item }) => {
    const preDetail = { ...(state.medRecordDetail || {}) }
    Object.assign(preDetail.MedRecord, item)
    return ({
      ...state,
      medRecordDetail: preDetail
    }
    )
  },
  [SET_MED_RECORD_FIELD.REQUEST]: (state, { field }) => {
    const preDetail = state.medRecordDetail
    const { MedRecord } = preDetail
    const { Fields } = MedRecord
    const { FieldName, FieldValue } = field
    if (!FieldName) return state
    Object.assign(Fields, { [FieldName]: FieldValue })
    return ({
      ...state,
      medRecordDetail: { ...preDetail, MedRecord: { ...MedRecord, Fields } }
    }
    )
  },
})
